package phidgetmotion.classifier;

import java.util.Iterator;
import java.util.LinkedList;

public abstract class AbstractClassifier implements Classifier {
	private int lastClassId = -1;
	private LinkedList<ClassChangeListener> classChangedListener = new LinkedList<ClassChangeListener>();
	private LinkedList<UpdateListener> updateListener = new LinkedList<UpdateListener>();

	@Override
	public void addClassChangeListener(ClassChangeListener l) {
		classChangedListener.add(l);
		l.classChanged(lastClassId);
	}

	@Override
	public void addUpdateListener(UpdateListener l) {
		updateListener.add(l);
		l.update(lastClassId);
	}
	
	@Override
	public boolean removeClassChangeListener(ClassChangeListener l) {
		return classChangedListener.remove(l);
	}

	@Override
	public boolean removeUpdateListener(UpdateListener l) {
		return updateListener.remove(l);
	}
	
	private void fireClassChanged(int classId){
		Iterator<ClassChangeListener> iter = classChangedListener.iterator();
		while(iter.hasNext()){
			iter.next().classChanged(classId);
		}
	}
	
	private void fireUpdate(int classId){
		Iterator<UpdateListener> iter = updateListener.iterator();
		while(iter.hasNext()){
			iter.next().update(classId);
		}
	}
	
	protected void update(int classId){
		fireUpdate(classId);
		if(classId!=lastClassId){
			lastClassId = classId;
			fireClassChanged(classId);
		}
	}

}
